package com.jy.horny.function.login

import android.content.Context
import android.content.Intent
import android.util.Log
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.common.api.ApiException
import com.jy.horny.base.BaseVMActivity
import com.jy.horny.base.HttpRequestListener
import com.jy.horny.databinding.ActivityLoginBinding
import com.jy.horny.model.LoginUserModel
import com.jy.horny.utils.UserUtil

/**
 * 登录页面
 */
class LoginActivity : BaseVMActivity<ActivityLoginBinding, LoginViewModel>(
    ActivityLoginBinding::inflate,
    LoginViewModel::class.java
) {
    private val GOOGLE_LOGIN = 1
    override fun initData() {
        binding.conLoginGoogle.setOnClickListener {
            val signInIntent = UserUtil.googleLogin(this).signInIntent
            startActivityForResult(signInIntent, GOOGLE_LOGIN)
//            RegisterActivity.start(this)
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when (requestCode) {
            GOOGLE_LOGIN -> {
                val task = GoogleSignIn.getSignedInAccountFromIntent(data)
                Log.e("~~~", "onActivityResult: ${task.isSuccessful}")

                try {
                    val account = task.getResult(ApiException::class.java)
                    mViewModel?.getLogin(object :HttpRequestListener<LoginUserModel>(){
                        override fun addRequestParams(params: HashMap<String, Any>) {
                            params["loginType"]=2
                            account.account?.name?.let { params["account"]= it }
                            account.email?.let { params["email"]= it }
                            account.displayName?.let { params["userName"]= it }
                        }

                        override fun success(t: LoginUserModel?) {

                        }

                    })
                } catch (e: ApiException) {
                    Log.e("~~~", "onActivityResult: "+e.localizedMessage )
                }
            }
        }
    }


    companion object {
        fun start(context: Context?) {
            context?.startActivity(Intent(context, LoginActivity::class.java))
        }
        fun startNew(context: Context?) {
            val intent = Intent(context, LoginActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            context?.startActivity(intent)
        }
    }
}